<?php
$dirList = explode('/', $_SERVER['PHP_SELF']);
require $_SERVER ["DOCUMENT_ROOT"] . "/$dirList[1]/conf/conf_env.php";

class Create_files {
	private $host;
	private $user;
	private $passwd;
	private $encode;
	
	// 构造函数
	public function Create_files() {
		$this->host =  "127.0.0.1";
		$this->user =  "root";
		$this->passwd =  "fan1989115";
		$this->encode =  "UTF8";
	}
	
	// 获取数据库连接
	public function getConn($db_name) {
		try {
			// 连接到Mysql
			$db = mysqli_connect ( $this->host, $this->user, $this->passwd );
			// 连接到数据库
			mysqli_query ( $db, "set names " . $this->encode );
			mysqli_select_db ( $db, $db_name );
			$this->conn = $db;
			return  $db;
		} catch ( Exception $e ) {
			throw e;
		}
	}
	
	public function getBrvFiles($dbName,$tableName) {
		$array = array();
		$conn = $this->getConn($dbName);
		$rs = mysqli_query($conn,"desc $tableName");
		if (!$rs){
			echo '找不到相应表或数据库，请检查参数<br>';
			return ;
		}
		$pre_key = "";
		$pre_key_fun_get = "";
		$pre_key_fun_set = "";
		while ( $arr_item = mysqli_fetch_assoc ( $rs ) ) {
			//print_r($arr_item);
			$array[] = $arr_item['Field'];
			if ($arr_item['Key'] == "PRI"){
				$pre_key = $arr_item['Field'];
				$pre_key_fun_get = "get" . ucfirst ( strtolower ( $pre_key ));
				$pre_key_fun_set = "set" . ucfirst ( strtolower ( $pre_key ) );
			}
		}
			
			
		$className = ucfirst (strtolower($tableName));
		$file_name = $_SERVER ["DOCUMENT_ROOT"] . '/tables/' . $className . '.php';
		$brvFile = fopen ( $file_name, 'a' );
		$str = "";
		
		
		// 大写变量，小写变量,set,get对
		$variable_upper = array ();
		$variable_lower = array ();
		$variable_fun_set = array ();
		$variable_fun_get = array ();
		
		for($i = 0; $i < count ( $array ); $i ++) {
			// $variable_upper2 [$i] = strtoupper ( $array [$i + 1] );
			$variable_upper [$i] = $array [$i];
			$variable_lower [$i] = strtolower ( $array [$i] );
			$variable_fun_set [$i] = "set" . ucfirst ( $variable_lower [$i] );
			$variable_fun_get [$i] = "get" . ucfirst ( $variable_lower [$i] );
		}
		
		$fun_set = array ();
		$fun_get = array ();
		
		for($i = 0; $i < count ( $array ); $i ++) {
			$fun_set [$i] = 'public function ' . $variable_fun_set [$i] . '($value) {
			       $this->array = array_merge ($this->array,array(
			       ' . "'" . $array [$i] . "' " . '=> $value));
		     	} ';
			$fun_get [$i] = 'public function ' . $variable_fun_get [$i] . '(){							
			      return $this->array [' . "'" . $array [$i] . "'" . '];
	            } ';
		}
		
		// 构造函数
		$constructor = 'public function ' . $className . '($array){	
									  
						$this->array = $array;
				
						 self::setDefault();
				
			   }';
		
		// setDefault（）函数
		$setDefault = 'private function setDefault(){
				
						 if(count($this->array)==0){
				';
		for($i = 0; $i < count ( $array ); $i ++) {
			$setDefault .= 'self::' . $variable_fun_set [$i] . '("");
					';
		}
		$setDefault .= '
							}
					}
				';
		
		// toInsertCSV()函数
		$toInserCSV = 'public function toInsertCSV() {
						 $str="";
				';
		for($i = 0; $i < count ( $array ); $i ++) {
			if ($i == count ( $array ) - 2 && ($array [$i] == 'CREATEDATE' || $array [$i] == 'createdate')) {
				$toInserCSV .= '
						// ' . $variable_lower [$i] . '
						$str .= "now()" . ",";
						';
			} else if ($i == count ( $array ) - 1 && ($array [$i] == 'UPDATEDATE' || $array [$i] == 'updatedate')) {
				$toInserCSV .= '
						// ' . $variable_lower [$i] . '
						$str .= "now()";
						';
			} else {
				if ($i == (count($array)-1)){
					$toInserCSV .= '
						// ' . $variable_lower [$i] . '
						$str .= "\'". self::' . $variable_fun_get [$i] . '();';
				}else {
					$toInserCSV .= '
						// ' . $variable_lower [$i] . '
						$str .= "\'". self::' . $variable_fun_get [$i] . '()."\',";';
				}
			}
		}
		$toInserCSV .= 'return $str;
						}
				';
		
		// toUpdateSet()函数
		$toUPdateSet = 'public function toUpdateSet() {
						 $str="";
				';
		for($i = 1; $i < count ( $array ); $i ++) {
			if ($i == count ( $array ) - 1 && ($array [$i] == 'UPDATEDATE' ||$array [$i] == 'updatedate')) {
				$toUPdateSet .= '
						// ' . $variable_lower [$i] . '
						$str .= "' . $variable_upper [$i] . ' = now()";
						';
			} else if ($i == count ( $array ) - 2 && ($array [$i] == 'CREATEDATE' || $array [$i] == 'createdate')) {
				$toUPdateSet .= '';
			} else {
				if ($i == (count($array)-1)){
					$toUPdateSet .= '
						// ' . $variable_lower [$i] . '
						$str'.".= '" . $variable_upper [$i] . " = \"' . self::" . $variable_fun_get [$i] . "();
						";
				}else {
					$toUPdateSet .= '
						// ' . $variable_lower [$i] . '
						$str'.".= '" . $variable_upper [$i] . " = \"' . self::" . $variable_fun_get [$i] . "() . '\",';
						";
				}
			}
		}
		$toUPdateSet .= 'return $str;
			    }
				';
		
		// toUpdateWhere() 函数
		$toUPdateWhere = 'public function toUpdateWhere(){
						 $str = ""; 
						$str .= "' . $pre_key . ' = \'" . self::' . $pre_key_fun_get . '()."\'";
						 return $str;
		        }
		';
		
		// getRecord函数
		$getRecord = 'public static function getRecord($id,$dbCon){
						 $where = "' . $pre_key . ' = \'$id\'' . '";
								 $record = SearchDb::getRecord
								 ($dbCon,static::$TABLENAME,$where);
								 if($record != null){
								 return new ' . $className . '($record);
				      		}
				      		 return null;
				      		 }
		';
		
		// getList函数
		$getList = 'public static function getList($dbCon) {
						 $where = "";
						 $list = SearchDb::getList($dbCon,static::$TABLENAME,$where);
						 $results = array();
						 
						foreach($list as $record){
						 array_push ( $results, new ' . $className . '($record));
								}
								 return $results;
	               }
';
		
		// getRecordMem函数
		$getRecordMem = 'public static function getRecordMem($id,$mstCon,$memCon) {
						 
						$listAll = self::getListMem ( $mstCon,$memCon);
						 
						foreach($listAll as $record) {
						
						if($record->' . $pre_key_fun_get . '() == $id){
								
								return $record;
								
								}
								}
								 return null;
								}
';
		
		// getListMem函数
		$getListMem = 'public static function getListMem($mstCon,$memCon){
						 
						$listAll = SearchDb::getListMem($mstCon,$memCon,static::$TABLENAME);
						 
						$results = array();
						 
						foreach($listAll as $record){
						 array_push ( $results,new ' . $className . '($record));
								 
					}
								 return $results; 
								 }
';
		
		if ($pre_key != ""){
			// insert函数
			//有主键
			$insert = 'public static function insert($record,$dbCon){
				
						try {
					
								$id = $record->' .  $pre_key_fun_get . '();
								$oldrecord = self::getRecord($id,$dbCon);
								if($oldrecord != null) {
								   throw new Exception ("重复插入");
								}
								ChangeDb::insert($dbCon,static::$TABLENAME,$record);
							} catch(Exception $e){
								throw $e;
								}
						}
';
		}else{
			// insert函数
			//无主键
			$insert = 'public static function insert($record,$dbCon){
						try {
								ChangeDb::insert($dbCon,static::$TABLENAME,$record);
							} catch(Exception $e){
								throw $e;
								}
						}
';
		}
		
		// update函数
		$update = 'public static function update($record ,$dbCon){
						try{
								$id = $record->' . $pre_key_fun_get . '();
								$oldrecord = self::getRecord($id,$dbCon);
								if($oldrecord == null){
										throw new Exception("不存在该记录");
								}
								ChangeDb::update($dbCon,static::$TABLENAME,$record);
						} catch(Exception $e){
										throw $e;
									}
					 }
';
		
		// delete函数
		$delete = 'public static function delete ($record,$dbCon){
						try{
							$id = $record->' . $pre_key_fun_get . '();
							$oldrecord = self::getRecord($id,$dbCon);
							if($oldrecord == null){
									throw new Exception("不存在该记录");
							}
							ChangeDb::delete($dbCon,static::$TABLENAME,$record);
						} catch(Exception $e){
									throw $e;
				        	}
					}
';
		
		// CLASS BEAN(基础类)
		$class_bean = 'class ' . $className . ' {
			
		    //数组	
			private $array;
			
					
			' . $constructor . '
		   
		   	
			' . $setDefault . '
			
		   				
			';
		
		for($i = 0; $i < count ( $array ); $i ++) {
			$class_bean .= '
					
				
			' . $fun_set [$i] . '
			' . $fun_get [$i];
		}
		
		
		if ($pre_key != ""){
			$class_bean .= '
		
			
			' . $toInserCSV . '
		
			
			' . $toUPdateSet . '
		
			
			' . $toUPdateWhere . "
}";
		}else{
			$class_bean .= '
		
			' . $toInserCSV . "
}";
		}
	
		
		
		// CLASS DAO (数据库操作类)
		$class_dao = 'class ' . $className . '_DAO {	
									
						private static $TABLENAME = ' . "'" . strtoupper ( $className ) . "'" . ';
								
								';
		
		
		if ($pre_key != ""){
			$class_dao .= '
			
			
				' . $getRecord . '
			
			
				' . $getList . '
			
			
			   ' . $getRecordMem . '
			
			
			   ' . $getListMem . '
			
			
			   ' . $insert . '
			
			
			   ' . $update . '
			
			
			   ' . $delete . '}';
		}else{
			$class_dao .= '
			
				' . $getList . '
			
			   ' . $getListMem . '
			
			
			   ' . $insert . '}';
		}

		
		
		// 生成文件信心
		$file_php_info = '<?php		
/**
 * 注：此模板为自动生成模板，需要根据实际情况调整修改
 * 此模板对 无主键/单一主键 表的支持较好，联合主键表在下一版本开发
 */					
' . $class_bean . '		
									
  	
' . $class_dao . '
										 
?>';
		
		fputs ( $brvFile, $file_php_info );
		fclose ( $brvFile );
	}
	
	public static function getStructureFiles($array) {
		$file_name = $_SERVER ["DOCUMENT_ROOT"] . '/tmp/' . $array [0] . '.php';
		$brvFile = fopen ( $file_name, 'a' );
		$str = "";
		
		// 大写变量，小写变量,set,get函数名
		$variable_upper = array ();
		$variable_lower = array ();
		$variable_fun_set = array ();
		$variable_fun_get = array ();
		// set,get函数体
		$fun_set = array ();
		$fun_get = array ();
		
		for($i = 0; $i < count ( $array ) - 1; $i ++) {
			$variable_upper [$i] = strtoupper ( $array [$i + 1] );
			$variable_lower [$i] = strtolower ( $array [$i + 1] );
			$variable_fun_set [$i] = "set" . ucfirst ( $variable_lower [$i] );
			$variable_fun_get [$i] = "get" . ucfirst ( $variable_lower [$i] );
			
			$fun_set [$i] = 'public function ' . $variable_fun_set [$i] . '($value) {
			       $this->array = array_merge ($this->array,array(
			       ' . "'" . $variable_lower [$i] . "' " . '=> $value));
		     	} ';
			$fun_get [$i] = 'public function ' . $variable_fun_get [$i] . '(){
			      return $this->array [' . "'" . $variable_lower [$i] . "'" . '];
	            } ';
		}
		
		// 构造函数
		$constructor = 'public function ' . $array [0] . '($json,$cnt){
						
						//默认配置
						 self::setDefault();
						
						//参数设置
						self::setParameter($json,$cnt);
	
			   }';
		
		// setDefault（）函数
		$setDefault = 'private function setDefault(){
	
				       $this->array = array();
				       ';
		for($i = 0; $i < count ( $array ) - 1; $i ++) {
			$setDefault .= 'self::' . $variable_fun_set [$i] . '("");
					    ';
		}
		$setDefault .= '
					}
	
				';
		
		// setParameter函数
		$setParameter = 'private function setParameter($json,$cnt){
				
				    foreach($json as $jkey => $jvalue){
						  if($jkey == static::$TAG_NAME){
							   foreach($jvalue[$cnt] as $key => $value){
									   BrvLog::debug(__FILE__,"[PARAM][KEY]" . $key . ":[VAL]" . $value);
									   if($key == P_' . $variable_upper [0] . ') {
									   		BrvLog::info(__FILE__, "[PARAM][KEY]" . LOG_P_' . $variable_upper [0] . ' . ":" . $value);
									   		self::' . $variable_fun_set [0] . '($value);
									    ';
		
		for($i = 1; $i < count ( $array ) - 1; $i ++) {
			$setParameter .= '} else if ($key == P_' . $variable_upper [$i] . '){
								            BrvLog::info(__FILE__, "[PARAM][KEY]" . LOG_P_' . $variable_upper [$i] . ' . ":" . $value);
								            self::' . $variable_fun_set [$i] . '($value);
							          ';
		}
		
		$setParameter .= '}
							       }
							}
					}
			}';
		
		// toArray函数
		$toArray = 'public function toArray() {
				     $crntArray = array (
			              ';
		
		for($i = 0; $i < count ( $array ) - 1; $i ++) {
			if ($i == count ( $array ) - 2) {
				// 最后个没有逗号
				$toArray .= 'P_' . $variable_upper [$i] . ' => self::' . $variable_fun_get [$i] . '()
				           ';
			} else {
				$toArray .= 'P_' . $variable_upper [$i] . ' => self::' . $variable_fun_get [$i] . '(),
				           ';
			}
		}
		$toArray .= ');
			    $crntArray = ArrayUtil::shuffle_save_key($crntArray);
			    return $crntArray;
	}';
		
		// CLASS BEAN(基础类)
		$class_bean = 'class ' . $array [0] . ' {
		
			//表名密码本
			public static $TAG_NAME = T_' . strtoupper ( $array [0] ) . ';
		    
		    //数组
			private $array;
		
			
			' . $constructor . '
		 
		   
			' . $setDefault . '
		    
		    
			' . $setParameter . '
		
		   
			';
		
		for($i = 0; $i < count ( $array ) - 1; $i ++) {
			$class_bean .= '
			
			
			' . $fun_set [$i] . '
			' . $fun_get [$i];
		}
		
		$class_bean .= '
				
				
				
			
			' . $toArray . '
}';
		
		// 生成文件内容
		$file_php_info = '<?php
   
' . $class_bean . '
						
?>';
		
		// 输入内容，生成文件
		fputs ( $brvFile, $file_php_info );
		fclose ( $brvFile );
	}
}

//**********************生成表************************************
$createFile = new Create_files();
$createFile->getBrvFiles("renren_nuo","rrn_admin_user");
$createFile->getBrvFiles("renren_nuo","rrn_mng_group_mst");
$createFile->getBrvFiles("renren_nuo","rrn_mng_page_mst");
echo "生成成功～";
?>